<?php

/**
 * 抽象通知者
 * Class Subject
 */
abstract class Subject
{
    private $observers = array();

    public function addObserver(Observer $observer)
    {
        array_push($this->observers, $observer);
    }

    public function delObserver($observer)
    {
        $index = array_search($observer, $this->observers);
        if($index !== false){
            unset($this->observers[$index]);
        }
    }

    public function Notify()
    {
        foreach ($this->observers as $v) {
            $v->update();
        }
    }
}

/**
 * 具体通知者
 * Class ConcreteSubject
 */
class ConcreteSubject extends Subject
{
    public $subjectState;
}


/**
 * 抽象观察者
 * Class Observer
 */
abstract class Observer
{
    public abstract function update();
}

class ConcreateObserver extends Observer
{
    private $subject;
    private $name;
    private $overState;

    public function __construct($name, ConcreteSubject $subject)
    {
        $this->name = $name;
        $this->subject = $subject;
    }

    public function update()
    {
        $this->overState = $this->subject->subjectState;
        echo '观察者:'.$this->name.',状态:'.$this->overState;
    }
}


$s = new ConcreteSubject();

$a = new ConcreateObserver("tang", $s);
$b = new ConcreateObserver("xiao", $s);

$s->addObserver($a);
$s->addObserver($b);

$s->subjectState = 'Boss回来了';
$s->Notify(); //发送给观察者